import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import * as CustomerViewAction from '../actions/customerView'
import * as CustomerCardRightMenuAction from '../actions/rightMenu' 
import * as SetRemindAction from '../actions/sellChanceMain'

import WeaRightLeftLayout from './weaCrmRightLeft'
import WeaFormmodeTop from './WeaFormmodeTop'
import ViewCustomerBase from './ViewCustomerBase'
import LeaveMessage from './customerCard/LeaveMessage.js'
import OutResourceList from './customerCard/OutResourceList.js'
import OutResourceView from './customerCard/OutResourceView.js'
import ViewCustomerShare from './customerCard/ViewCustomerShare.js'
import ViewLog from './customerCard/ViewLog.js'
import ViewAddress from './customerCard/ViewAddress.js'
import ListSellChance from './customerCard/ListSellChance.js'
import CustomerEvaluation from './customerCard/CustomerEvaluation.js'
import CustomerContact from './CustomerContact.js'
import ContractQuery from './ContractQuery.js'
import RemindSetModal from './contact/remindSetModal'
import {WeaTab, WeaLeftTree,WeaSearchGroup,WeaRightMenu,WeaAlertPage} from 'ecCom'

import {WeaErrorPage,WeaTools} from 'ecCom'

import {Button,Form,Modal,message,Spin} from 'antd' 
const createForm = Form.create;
const FormItem = Form.Item;

import cloneDeep from 'lodash/cloneDeep'
import objectAssign from 'object-assign'
import forEach from 'lodash/forEach'
import isEmpty from 'lodash/isEmpty'

import PropTypes from 'react-router/lib/PropTypes'
import Immutable from 'immutable'
const is = Immutable.is;
let _this = null;

class CustomerView extends React.Component {
    constructor(props) {
		super(props);
		_this = this;
    }
    componentDidMount() {
        const {actions,location:{query}} = this.props;
        actions.setNowRouterCmpath('customerView');
        actions.initDatas(query);
    }
    componentWillReceiveProps(nextProps) {
        const oldCustomerid = this.props.location.query.customerId;
        const newCustomerid = nextProps.location.query.customerId;
        if(oldCustomerid != newCustomerid){
            const {actions,location:{query}} = nextProps.props;
            actions.initDatas(query);
        }

    
    }
    shouldComponentUpdate(nextProps,nextState) {
        return !is(this.props.title,nextProps.title)||
        !is(this.props.detailTabKey,nextProps.detailTabKey)||
        !is(this.props.conditioninfo,nextProps.conditioninfo)||
        !is(this.props.loading,nextProps.loading)||
        !is(this.props.tabDatas,nextProps.tabDatas)||
        !is(this.props.tabId,nextProps.tabId)||
        !is(this.props.rcList,nextProps.rcList)||
        !is(this.props.customerId,nextProps.customerId)||
        !is(this.props.remindInfo,nextProps.remindInfo)||
        !is(this.props.customereEvalRcList,nextProps.customereEvalRcList)||
        !is(this.props.rightLevel,nextProps.rightLevel)||
        !is(this.props.hasright,nextProps.hasright);
    }
    componentWillUnmount(){
    	// const {actions,isClearNowPageStatus} = this.props;
        // actions.unmountClear(isClearNowPageStatus);
        // actions.isClearNowPageStatus(false);
    }
    render() {
        let that = this;
        const {loading,actions,title,conditioninfo,detailTabKey,tabDatas,tabId,location,remindInfo,customerId,hasright,rightLevel} = this.props;
         if(hasright == "-1"){
            return (
				<div className="align-center top40">
					<Spin size="large"></Spin>
				</div>);
        }else if(!hasright){
            return (
                <WeaAlertPage>
                    <div className="color-black">
                        对不起，您暂时没有权限
                    </div>
                </WeaAlertPage>)
        }else{
            const tabDatas1 = tabDatas.toJS();
            let tabUrl = function(key){
                   if(tabDatas1){
                        for(let i=0;i<tabDatas1.length;i++){
                           if(tabDatas1[i].id == key && tabDatas1[i].shortname=="baseinfo"){   //基本信息
                               return <ViewCustomerBase rightLevel={rightLevel} location={location}/>
                           }else if(tabDatas1[i].id == key && tabDatas1[i].shortname=="contactinfo"){   //客户联系
                               return  <CustomerContact params={{from:"all"}}  location={location}/>
                           }else if(tabDatas1[i].id == key && tabDatas1[i].shortname=="outresourceinfo"){ //外部用户
                               return  <OutResourceList   location={location}/>
                           }else if(tabDatas1[i].id == key && tabDatas1[i].shortname=="shareinfo"){   //共享设置
                               return  <ViewCustomerShare location={location} />
                           }else if(tabDatas1[i].id == key && tabDatas1[i].shortname=="loginfo"){   //修改记录
                               return  <ViewLog location={location} />
                           }else if(tabDatas1[i].id == key && tabDatas1[i].shortname=="addressinfo"){  //地址管理
                               return  <ViewAddress location={location}/>
                           }else if(tabDatas1[i].id == key && tabDatas1[i].shortname=="sellchanceinfo"){   //商机管理
                               return  <ListSellChance location={location} />
                           }else if(tabDatas1[i].id == key && tabDatas1[i].shortname=="evaluationinfo"){   //客户价值
                               return  <CustomerEvaluation ref="customerEvaluation" location={location}  />
                           }else if(tabDatas1[i].id == key && tabDatas1[i].shortname=="exchangeinfo"){   //客户留言
                             return  <LeaveMessage location={location} />
                           }else if(tabDatas1[i].id == key && tabDatas1[i].shortname=="contractinfo"){   //合同管理
                             return  <ContractQuery location={location} />
                           }else if(tabDatas1[i].id == key && tabDatas1[i].shortname==""){
                               return  tabDatas1[i].linkurl;
                           }
                        }
                        return ""
                    }
                }(tabId);
            return (
                <div className="crm-top-req">
                    <WeaFormmodeTop
                        title={title}
                        loading={loading}
                        icon={<i className='icon-coms-crm' />}
                        tabDatas={tabDatas1}
                        selectedKey={detailTabKey}
                        onChange={this.changeData.bind(this)}
                        iconBgcolor='#96358a'
                        buttons={this.getButtons()}
                        buttonSpace={10}
                        showDropIcon={false}
                    dropMenuDatas={this.getRightMenu()}
                    onDropMenuClick={this.onRightMenuClick.bind(this)}
                    >
                    {
                        typeof tabUrl === "object" ?  tabUrl:
                        <iframe src={tabUrl} id="tabcontentframe" name="tabcontentframe" className="flowFrame" frameborder="0"  height="100%" width="100%;" />
                    }
                    </WeaFormmodeTop>
                    <RemindSetModal ref="remindSetInCustomerCard" remindInfo={remindInfo} customerId={customerId} saveRemindSetting={this.saveRemindSetting}/>
                </div>
            )
        }
    }
    changeData(key){
        const {actions} = this.props
       actions.setDetailTabKey(key);
   }
    getButtons() {
        const {actions,rcList,tabDatas,tabId,customerContactRcList} = this.props;
        let btnArr = [];
        tabDatas.toJS().map(item=>{
            if( item.key == tabId && item.shortname == "contactinfo"){
                btnArr.push((<Button type="primary" onClick={this.setContactRemind.bind(this)}>联系提醒设置</Button>));
            }

        })
        return btnArr
    }

    getRightMenu(){
        const {actions,rcList,tabDatas,tabId,customerContactRcList,customereEvalRcList} = this.props;
        let btns = [];   
        tabDatas.toJS().map(item=>{
           if( item.key == tabId && item.shortname == "baseinfo"){
                rcList.toJS().map(item=>{
                    let _icon="icon-coms-Need-feedback"
                    if(item.key == "2"){   //导出客户联系
                        _icon="icon-coms-export "
                    }else if(item.key == "3"){  //新建邮件
                        _icon="icon-coms-Send-emails"
                    }else if(item.key == "39"){  //新建工作流
                        _icon="icon-coms-Workflow"
                    }else if(item.key == "40"){  //新建协作事件
                        _icon="icon-coms-synergism "
                    }else if(item.key == "41"){  //新建计划
                        _icon="icon-coms-Planning-tasks"
                    }else if(item.key == "42"){  //客户合并
                        _icon="icon-coms-HumanResources"
                    }
                    return  btns.push({
                        icon: <i className={_icon}/>,
                        content:`${item.content}`,
                        key:`${item.key}`,
                        onClick:key =>{eval("actions." + `${item.fn}`);}
                    });
                })
           }
           if(item.key == tabId && item.shortname == "contactinfo"){
                customerContactRcList && !is(customerContactRcList,Immutable.fromJS([])) && customerContactRcList.map(m=>{
                    btns.push({
                        icon: <i className={m.get('menuIcon')} />,
                        content: m.get('menuName'),
                        disabled : false
                    })
                });
           }
           if(item.key == tabId && item.shortname == "outresourceinfo"){
            // customerContactRcList && !is(customerContactRcList,Immutable.fromJS([])) && customerContactRcList.map(m=>{
            //     btns.push({
            //         icon: <i className={m.get('menuIcon')} />,
            //         content: m.get('menuName'),
            //         disabled : false
            //     })
            // });
            }
            if(item.key == tabId && item.shortname == "evaluationinfo"){
                customereEvalRcList && !is(customereEvalRcList,Immutable.fromJS([])) && customereEvalRcList.map(m=>{
                    btns.push({
                        icon: <i className={m.get('menuIcon')} />,
                        content: m.get('menuName'),
                        disabled : false
                    })
                });
            }
        })
        
    	return btns
    }
    onRightMenuClick(key){
        const {actions,comsWeaTable,dataKey,customerId,tabDatas,tabId,customereEvalRcList} = this.props;
        tabDatas.toJS().map(item=>{
            if( item.key == tabId && item.shortname == "baseinfo"){
                if(key == '2'){  //导出客户联系
                    actions.contactLogExport(customerId);
                }
                if(key == '3'){  //新建邮件
                    actions.addMailMenu(customerId);
                }
                if(key == '39'){  //新建工作流
                  //actions.addMailMenu(customerId);
                }
                if(key == '40'){  //新建协作事件
                 //actions.addMailMenu(customerId);
               }
               if(key == '41'){  //新建计划
                 //actions.addMailMenu(customerId);
               }
               if(key == '44'){  //客户合并
                 const modalInfo={
                     modalTitle:"客户合并",
                     modalStyle:{width: 446, height: 180},
                     modalType:"customerMerge"
                 };
                 actions.getUniteForm(customerId);
                 actions.setModalBaseInfo(modalInfo);
                 actions.showDilog(true);
               }
               if(key == '45'){  //修改密码
                 const modalInfo={
                     modalTitle:"设置密码",
                     modalStyle:{width: 446, height: 240},
                     modalType:"setPasswd"
                 };
                 actions.setModalBaseInfo(modalInfo);
                 actions.showDilog(true);
                }
                if(key == '4'){  //删除
                 actions.deleteCustomer(customerId);
                }
                if(key == '46'){  //工商信息
                 actions.getBusinessInfo(customerId);
               }
            }
            if(item.key == tabId && item.shortname == "contactinfo"){
                
            }
            if(item.key == tabId && item.shortname == "evaluationinfo"){
                //customerEvaluation
                customereEvalRcList && !is(customereEvalRcList,Immutable.fromJS([])) && customereEvalRcList.map((m,i)=>{
                    if(Number(key) == i){
                        let fn = m.get('menuFun').indexOf('this') >= 0 ? `${m.get('menuFun').split('this')[0]})` : m.get('menuFun');
                        if(fn == ""){
                            if(m.get('type') == "BTN_UPDATE"){ //更新
                                console.log(this.refs.customerEvaluation)
                                //actions.evaluationUpdate({customerId:customerId,...params});
                            }
                        }else{
                           
                        }
                    }
                });
            }
        })
        
   }
   setContactRemind(){
        const {actions,customerId} = this.props;
        actions.getRemindInfo(customerId);
        this.refs.remindSetInCustomerCard.setContactVisible(true);
   }
   saveRemindSetting=(params)=>{
     // console.log(params,SetRemindAction);
      const {actions} = this.props;
      actions.saveRemindSet(params);
   }
}


class MyErrorHandler extends React.Component {
    render(){
        const hasErrorMsg = this.props.error && this.props.error!=="";
        return (
            <WeaErrorPage msg={hasErrorMsg?this.props.error:"对不起，该页面异常，请联系管理员！"} />
        );
    }
}

CustomerView = WeaTools.tryCatch(React, MyErrorHandler, {error: ""})(CustomerView);

CustomerView = createForm({
	// onFieldsChange(props, fields) {
    //     console.log(fields)
    //     props.actions.saveOrderFields({...props.orderFields.toJS(), ...fields});
    // },
	// mapPropsToFields(props) {
	// 	return props.orderFields.toJS();
  	// }
})(CustomerView);

function mapStateToProps(state) {
	const {crmcustomerView,viewCustomerBase,crmcustomerContact} = state;
    return {
    	loading: crmcustomerView.get('loading'),
        title: crmcustomerView.get('title'),
        conditioninfo: crmcustomerView.get('conditioninfo'),
        detailTabKey: crmcustomerView.get('detailTabKey'),
        tabDatas:crmcustomerView.get('tabDatas'),
        tabId:crmcustomerView.get('tabId'),
        customerId:crmcustomerView.get('customerId'),
        remindInfo:crmcustomerView.get('remindInfo'),
        hasright:crmcustomerView.get('hasright'),
        rightLevel:crmcustomerView.get('rightLevel'),
        // searchParamsAd: crmContactQuery.get('searchParamsAd'),
        rcList: viewCustomerBase.get('rcList'),
        customerContactRcList:crmcustomerContact.get('customerContactRcList'),
        customereEvalRcList:crmcustomerView.get('customereEvalRcList')
    }
}

function mapDispatchToProps(dispatch) {
    return {
        actions: bindActionCreators({...CustomerViewAction,...CustomerCardRightMenuAction}, dispatch)
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(CustomerView);
